package network;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpEchoClient {
    private DatagramSocket socket = null;
    private String serverIp;//服务器IP
    private int serverPort;//服务器端口

    //参数的是 服务器的IP和端口
    public UdpEchoClient(String serverIp,int serverPort) throws SocketException {
        //客户端一般不要手动指定端口 空闲端口
        socket = new DatagramSocket();
        this.serverIp = serverIp;
        this.serverPort = serverPort;
    }

    public void start() throws IOException {
        System.out.println("客户端~启动！！");
        Scanner scanner = new Scanner(System.in);
        while(true){
            System.out.print("-> ");
            //1.从控制台读取要发送的请求数据
            //控制台读取 推荐使用next（），而不是nextLine（） 文件读取随意
            if(!scanner.hasNext()){
                break;
            }
            String request = scanner.next();

            //2.构造请求并发送
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),
                    request.getBytes().length,
                    InetAddress.getByName(serverIp),serverPort);
            socket.send(requestPacket);

            //3.读取服务器的响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);

            //4.把响应显示到控制台
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1",9090);
        client.start();
    }
}
